<?php
require_once './include/common.inc.php';
require_once PPCHAT_ROOT . './include/json.php';
//require_once './admin/function.php';

$json = new JSON_obj;
$uid = (int) $uid;
$id = (int) $id;

$tempcount = 0;
switch ($act) {
    case "setdefvideosrc";
        $db->query("update {$tablepre}config set defvideo='$vid',defvideonick='$nick' where id='$rid'");
        break;
    case "setTitleNotice";
        $db->query("update {$tablepre}notice set txt='$txt' where id='7'");
        break;
    //私聊聊天记录
    case "mymsgold":
        $uid = $_SESSION['login_uid'];
        $query = $db->query("select *  from {$tablepre}msgs where (uid='$uid' and tuid='$tuid')or(uid='$tuid' and tuid='$uid') and type='0' order by id desc limit 0,20");
        while ($row = $db->fetch_row($query)) {
            $str1 = '
                <li class="layim_chate[me]"><div class="layim_chatuser"><span class="layim_chattime">[date]</span><span class="layim_chatname">[uname]</span><img src="../face/img.php?t=p1&u=[uid]"></div><div class="layim_chatsay"><font style="color:#000">[msg]</font><em class="layim_zero"></em></div></li>
                ';
            $str2 = '
                <li class="layim_chate[me]"><div class="layim_chatuser"><img src="../face/img.php?t=p1&u=[uid]"><span class="layim_chatname">[uname]</span><span class="layim_chattime">[date]</span></div><div class="layim_chatsay"><font style="color:#000">[msg]</font><em class="layim_zero"></em></div></li>
                ';
            if ($row['uid'] == $uid)
                $str = str_replace("[me]", "me", $str1);
            else
                $str = str_replace("[me]", "he", $str2);
            $str = str_replace("[uid]", $row['uid'], $str);
            $str = str_replace("[uname]", $row['uname'], $str);
            $str = str_replace("[msg]", tohtml($row['msg']), $str);
            $str = str_replace("[date]", date("Y-m-d H:i:s", $row['mtime']), $str);
            $msgold = $str . $msgold;
        }
        empty($msgold) && exit();
        $data['realname'] = userinfo($tuid, '{realname}');
        $data['tuid'] = $tuid;
        $data['msg'] = $msgold;
        exit($json->encode($data));
        break;
    //屏蔽消息
    case "msgblock":
        $db->query("update {$tablepre}msgs set state='$s' where msgid='$msgid'");
        exit();
        break;
    //我的客服
    case "getmylist":
        //print_r($_GET);exit();
        $i = 0;
        $fuser = userinfo($_SESSION['login_uid'], '{fuser}');
        if ($fuser == "")
            $fuser = $cfg['config']['defkf'];
        $query = $db->query("select m.*,ms.* from {$tablepre}members m left join {$tablepre}memberfields ms
                          on m.uid=ms.uid where m.username ='$fuser'");
        while ($row = $db->fetch_row($query)) {
            $tmp['uid'] = $row['uid'];
            $tmp['chatid'] = $row['uid'];
            $tmp['nick'] = $row['nickname'];
            $tmp['phone'] = $row['phone'];
            $tmp['qq'] = $row['realname'];
            $tmp['gid'] = $row['gid'];
            $data['row'][$i++] = $tmp;
        }

        $query = $db->query("select m.*,ms.* from {$tablepre}members m left join {$tablepre}memberfields ms
                          on m.uid=ms.uid   where m.fuser='{$user}'");
        while ($row = $db->fetch_row($query)) {
            $tmp['uid'] = $row['uid'];
            $tmp['chatid'] = $row['uid'];
            $tmp['nick'] = $row['nickname'];
            $tmp['phone'] = $row['phone'];
            $tmp['qq'] = $row['realname'];
            $tmp['gid'] = $row['gid'];
            $data['row'][$i++] = $tmp;
        }
        $data['state'] = 'true';
        exit($json->encode($data));
        break;
    case "getrlist":

        //机器人列表
        //$rid:房间ID $r:20|50 20-50随机数 机器人个数
        $r = explode("|", $r);
        $r_max = rand(18, 23);
        if ($r_max <= 0)
            exit("");
        $time = time();
        $query = $db->query("select * from {$tablepre}rebots where rid='$rid' and losttime>{$time}");
        if ($db->num_rows($query) <= 0) {
            $query = $db->query("select * from {$tablepre}rebots where id='1'");
            $row = $db->fetch_row($query);
            $rebots_arr = explode("\r\n", $row['rebots']);
            shuffle($rebots_arr);

            $roomListUser = array();
            $roomUser = array("roomid" => $_SERVER['HTTP_HOST'] . "." . $rid, "chatid" => "", "ip" => "0.0.0.0", "qx" => "0", "cam" => "", "vip" => "0", "age" => "-", "sex" => "", "mood" => "", "state" => "0", "nick" => "", "color" => "0");
            $count = count($rebots_arr);
            $roomListUserJsonStr = array("type" => "UonlineUser", "stat" => "OK", "count" => $r_max);

            $count = $count>1000?$count:1000;

            for ($i = 0; $i < $count; $i++) {
                if (trim($rebots_arr[$i]) == "")
                    continue;
                $roomUser['chatid'] = 'x_r' . $i;
                $roomUser['sex'] = rand(0, 2);
                $roomUser['cam'] = rand(0, 2);
                $roomUser['nick'] = $rebots_arr[$i];
                $roomListUser[$i] = $roomUser;

                if ($i >= $r_max)
                    break;
            }
            $roomListUserJsonStr['roomListUser'] = $roomListUser;
            $data = base64_encode($json->encode($roomListUserJsonStr));
            //机器人列表20分钟一换
            $losttime = time() + 1 * 60;
            $db->query("delete from {$tablepre}rebots where rid='$rid'");
            $db->query("insert into {$tablepre}rebots(rid,rebots,losttime)values('$rid','$data','$losttime')");
        }
        else {
            //获取有效列表
            $row = $db->fetch_row($query);
            $data = $row['rebots'];
        }

        exit(base64_decode($data));
        break;
    case "putmsg":
        $msg = $_POST[msg];
        if ($cfg['config']['msgaudit'] == '1'  && (!preg_match('/<img src=\\\"\/room\/face\/colorbar\/[a-z]{2,6}.gif\\\">/i', $msg) && !preg_match('/(\/room\/skins\/chatimg\/[A-Za-z][A-Za-z]*)/i', $msg) && !preg_match('/(<img src=\\\"\/room\/face\/pic\/[0-9a-z_]{2,11}.gif\\\">){8}/i', $msg))) {
            $state = '1';
        }
        if ($msgtip == "2")
            $state = '2';
        if ($msgtip == "3")
            $state = '3';
        if ($qx == "1")
            $state = '0';
        if($muid != $_SESSION['login_uid']) {
            $gid = 0;
        } else {
            $gid = $_SESSION['login_gid'];
        }


        $sql = "insert into {$tablepre}msgs(rid,uid,tuid,uname,tname,p,style,msg,mtime,ugid,msgid,ip,state)
                  values('$rid','$muid','$tid','$uname','$tname','$privacy','$style','$_POST[msg]'," . gdate() . ",'$gid','$msgid','$onlineip','$state')";
        $db->query($sql);
        break;
    case "regcheck":
        $guestexp = '^Guest|' . $cfg['config']['regban'] . "Guest";
        if (preg_match("/\s+|{$guestexp}/is", $username))
            exit('-1');

        if ($db->num_rows($db->query("select * from {$tablepre}members where username='$username' ")) > 0)
            exit('0');
        else
            exit('1');
        break;
    case "setvideo":
        $uid = $_SESSION['login_uid'];
        if (check_auth('room_admin')) {
            $db->query("update {$tablepre}config set defvideo='{$vid}' where id='{$def_cfg}'");
        }
        break;
    case "userstate":
        if (isset($_SESSION['login_uid'])) {
            $userstate['state'] = "login";
            $id = $_SESSION['login_uid'];
            $query = $db->query("select m.uid,m.sex,m.onlinetime,m.gold,ms.nickname,ms.mood,ms.city,ms.bday
                          from {$tablepre}members m,{$tablepre}memberfields ms
                          where m.uid=ms.uid and m.uid='{$id}'
                          ");
            $row = $db->fetch_row($query);
            $userinfo['id'] = $row['uid'];
            $userinfo['nick'] = $row['nickname'];
            $userinfo['sn'] = $row['mood'];
            $userinfo['rank'] = showstars($row['onlinetime']);
            $userinfo['gold'] = $goldname . ':' . $row['gold'];
            $userstate['info'] = $userinfo;
        } else {
            $userstate['state'] = "logout";
        }
        $data = $json->encode($userstate);
        exit($data);
        break;
    case "userinfo":
        $query = $db->query("select m.*,ms.*
                          from {$tablepre}members m,{$tablepre}memberfields ms
                          where m.uid=ms.uid and m.uid='{$id}'
                          ");
        $row = $db->fetch_row($query);
        $row['password'] = '';
        $data = $json->encode($row);
        exit($data);
        break;
    case "delimpression":
        if (!isset($_SESSION['login_uid']) || $_SESSION['login_uid'] == 0)
            $state['state'] = 'logout';
        else {
            $uid = $_SESSION['login_uid'];
            $db->query("delete from {$tablepre}membersapp1 where uid='$uid' and fuid='$fuid' and ftime='$ftime'");
            $state['state'] = 'ok';
        }
        $data = $json->encode($state);
        exit($data);
        break;
    case "impression":
        if (!isset($_SESSION['login_uid']) || $_SESSION['login_uid'] == 0)
            $state['state'] = 'logout';
        else {
            $color = rand_color();
            $time = gdate();
            $fuid = $_SESSION['login_uid'];
            $db->query("delete from {$tablepre}membersapp1 where uid='$uid' and fuid='$fuid'");
            $sql = "insert into {$tablepre}membersapp1(uid,color,txt,fuid,ftime)
                  values('$uid','$color','$t','$fuid','$time')";
            $db->query($sql);
            $state['state'] = 'ok';
        }
        $data = $json->encode($state);
        exit($data);
        break;
    case "memberfriends":
        if (!isset($_SESSION['login_uid']))
            $state['state'] = 'logout';
        else {
            $ftime = gdate();
            $uid = $_SESSION['login_uid'];
            if (isset($a))
                $db->query("replace into {$tablepre}membersapp3(uid,fuid,ftime)values('$uid','$a','$ftime')");
            if (isset($d))
                $db->query("delete from {$tablepre}membersapp3 where uid='$uid' and fuid='$d'");
            $state['state'] = 'ok';
        }
        $data = $json->encode($state);
        exit($data);
        break;
    case "message":
        if (!isset($_SESSION['login_uid']) || $_SESSION['login_uid'] == 0)
            $state['state'] = 'logout';
        else {
            if (isset($d)) {
                $db->query("delete from {$tablepre}membersapp4 where id='$d' and uid='$_SESSION[login_uid]'");
                $state['state'] = 'ok';
            } else {
                if (trim($txt) != '') {
                    $txt = $db->totxt($txt);
                    $ftime = gdate() - 2;
                    $fuid = $_SESSION['login_uid'];
                    $db->query("insert into {$tablepre}membersapp4(uid,fuid,ftime,tag,txt)values('$uid','$fuid','$ftime','$tag','$txt')");
                }
                $state['state'] = 'ok';
            }
        }
        $data = $json->encode($state);
        exit($data);

        break;
    case "kick":
        if (check_user_auth($aid, 'user_kick')) {
            $losttime = (int)$ktime * 60 + gdate();
            $db->query("insert into {$tablepre}ban(username,ip,losttime,sn)values('$u','$onlineip','$losttime','$cause')");
            $state['state'] = 'yes';

            //全员屏蔽状态
            $get_data['ToChatId'] = $tid;
            $get_data['reson'] = $cause;
            $get_data['ktime'] = (int)$ktime;
            $time_res = curl_get($get_data, 'kick',$liveapi_url);

            $data = $json->encode($state);
            exit($data);
        }

        break;
    case "kick_send":
        if (check_user_auth($aid, 'user_send')) {
            $db->query("insert into {$tablepre}send(username,ip)values('$u','$onlineip')");
            $state['state'] = 'yes';
            $data = $json->encode($state);
            exit($data);
        }
        break;
    case "online":



        if (!isset($_SESSION['login_uid']))
            $state['state'] = 'logout';
        else {
            if ($_SESSION['login_uid'] == 0) {
                $state['state'] = 'ok';
                $data = $json->encode($state);
                exit($data);
            }
            if (!empty($rst)) {
                $time = gdate();
                $u_id = $_SESSION['login_uid'];
                $query_row = $db->fetch_row($db->query("select lastactivity from {$tablepre}members where uid='$u_id'"));
                $_time = (int) ($time - $query_row['lastactivity']);
                $rid = $_SESSION['onlines_state']['rid'];
                $query = $db->query("select * from {$tablepre}memberonlines where rst='$rst' and uid='$u_id'");
                if ($db->num_rows($query) <= 0) {
                    $db->query("replace into {$tablepre}memberonlines(uid,rid,lastactivity,ip,rst)values('$u_id','$rid','$time','$onlineip',$rst)");
                    $state['state'] = 'ologin';
                    $data = $json->encode($state);
                    exit($data);
                }
                $db->query("update {$tablepre}memberonlines set lastactivity='$time' where rst='$rst' and uid='$u_id'");
                $db->query("update {$tablepre}members set lastactivity='$time',onlinetime=onlinetime+$_time where uid='$u_id'");
                $state['state'] = 'ok';
                $onlineNum = (int) $num;
//                if ($num >= 1)
//                    $db->query("update {$tablepre}config set online='$num' where id='$def_cfg'");
            }
            else {
                reonline();
                $state['state'] = 'ok';
            }
        }

        $data = $json->encode($state);
        exit($data);

        break;
    case "postGif":
        $uid = $_SESSION['login_uid'];
        $diamond = $_REQUEST[diamond];
        $gift_id = $_REQUEST[gift_id];
        $gift_name = $_REQUEST[gift_name];
        $nick = $_REQUEST[nick];
        $num = $_REQUEST[num];
        $time = time();
        $msg = $nick.'送出'.$num.'个'.$gift_name;

        $db->query("INSERT INTO `chat_gold_log` (`gid`, `gname`, `uid`, `uname`, `touid`, `touname`, `msg`, `dateline`, `num`, `cost`, `type`) VALUES ('$gift_id', '$gift_name', '$uid', '$nick', '0', NULL, '$msg', '$time', '$num','$diamond','1')");

        //扣除钻石
        return $db->query("update {$tablepre}members set  diamond = diamond - $diamond where uid='{$uid}'");

        break;
}

function curl_get($get_data, $url, $base_url){
    $url = $base_url . "/"  . $url;
    $params_str = http_build_query($get_data);
    $url = $url . "?" . $params_str;
    $ch = curl_init($url) ;
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ; // 获取数据返回
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, true) ;
    curl_setopt($ch, CURLOPT_TIMEOUT, 20) ;
    // 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回
    $output = curl_exec($ch) ;
    return $output;
}
?>